{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "4 Pandas 的索引操作",
   "id": "1253cd6823b9e760"
  },
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-01-07T06:21:45.715583Z",
     "start_time": "2025-01-07T06:21:45.707Z"
    }
   },
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "dict_data = {'A': 1,\n",
    "             'B': pd.Timestamp('20190926'),\n",
    "             'C': pd.Series(1,index=list(range(4)),dtype='float32'),\n",
    "             'D': np.array([3] * 4,dtype='int32'),\n",
    "             'E': [\"Python\",\"Java\",\"C++\",\"C\"],\n",
    "             'F': 'wangdao' }\n",
    "#print(dict_data)\n",
    "df_obj2 = pd.DataFrame(dict_data)\n",
    "ser_obj = pd.Series(range(10, 20))\n",
    "print(type(ser_obj.index))\n",
    "print(type(df_obj2.index))\n",
    "print(df_obj2.index)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.indexes.range.RangeIndex'>\n",
      "<class 'pandas.core.indexes.base.Index'>\n",
      "Index([0, 1, 2, 3], dtype='int64')\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:22:03.840078Z",
     "start_time": "2025-01-07T06:22:03.092489Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 索引对象不可变（上面代码增加）\n",
    "df_obj2.index[0] = 2"
   ],
   "id": "af7beffa47d9e3c6",
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "Index does not support mutable operations",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mTypeError\u001B[0m                                 Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[4], line 2\u001B[0m\n\u001B[0;32m      1\u001B[0m \u001B[38;5;66;03m# 索引对象不可变（上面代码增加）\u001B[39;00m\n\u001B[1;32m----> 2\u001B[0m \u001B[43mdf_obj2\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mindex\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;241;43m0\u001B[39;49m\u001B[43m]\u001B[49m \u001B[38;5;241m=\u001B[39m \u001B[38;5;241m2\u001B[39m\n",
      "File \u001B[1;32mD:\\pycharm解释器\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:5371\u001B[0m, in \u001B[0;36mIndex.__setitem__\u001B[1;34m(self, key, value)\u001B[0m\n\u001B[0;32m   5369\u001B[0m \u001B[38;5;129m@final\u001B[39m\n\u001B[0;32m   5370\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m \u001B[38;5;21m__setitem__\u001B[39m(\u001B[38;5;28mself\u001B[39m, key, value) \u001B[38;5;241m-\u001B[39m\u001B[38;5;241m>\u001B[39m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[1;32m-> 5371\u001B[0m     \u001B[38;5;28;01mraise\u001B[39;00m \u001B[38;5;167;01mTypeError\u001B[39;00m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mIndex does not support mutable operations\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n",
      "\u001B[1;31mTypeError\u001B[0m: Index does not support mutable operations"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:23:19.490444Z",
     "start_time": "2025-01-07T06:23:19.481650Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# index 指定行索引名\n",
    "ser_obj = pd.Series(range(5), index = ['a', 'b', 'c', 'd', 'e'])\n",
    "print(ser_obj.head())"
   ],
   "id": "e3e5590449d13776",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:24:02.710822Z",
     "start_time": "2025-01-07T06:24:02.704886Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#行索引\n",
    "print(ser_obj['b'])\n",
    "print(ser_obj[2])"
   ],
   "id": "e8147eed52dd9718",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\余彬\\AppData\\Local\\Temp\\ipykernel_20748\\3692629748.py:3: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
      "  print(ser_obj[2])\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:27:30.337162Z",
     "start_time": "2025-01-07T06:27:30.324817Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 切片索引\n",
    "print(ser_obj.iloc[1:3])\n",
    "print(ser_obj.loc['b':'d'])"
   ],
   "id": "30f8bf5a24d1c401",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b    1\n",
      "c    2\n",
      "dtype: int64\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:27:21.520979Z",
     "start_time": "2025-01-07T06:27:21.512313Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 不连续索引\n",
    "print(ser_obj.iloc[[0, 2, 4]])\n",
    "print(ser_obj.loc[['a', 'e']])"
   ],
   "id": "5b1d5e010fcd6533",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "c    2\n",
      "e    4\n",
      "dtype: int64\n",
      "a    0\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:32:39.799687Z",
     "start_time": "2025-01-07T06:32:39.779884Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#DataFrame 索引\n",
    "#columns 指定列索引名\n",
    "df_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd'])\n",
    "print(df_obj.head())"
   ],
   "id": "b9dfd6bc19321da5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          a         b         c         d\n",
      "0  0.585889  1.786924  0.439963  0.458170\n",
      "1 -0.366636 -0.560111 -1.367335 -0.118685\n",
      "2 -0.847734  0.297635 -0.462312 -0.195054\n",
      "3 -0.185211  1.111763 -0.849396 -2.269203\n",
      "4  0.846920  0.664801  0.137463  1.193840\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:33:12.386689Z",
     "start_time": "2025-01-07T06:33:12.374683Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 列索引\n",
    "print(df_obj['a']) # 返回 Series 类型\n",
    "print(df_obj[['a']]) # 返回 DataFrame 类型\n",
    "print(type(df_obj[['a']])) # 返回 DataFrame 类型"
   ],
   "id": "854a99a1826a4462",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    0.585889\n",
      "1   -0.366636\n",
      "2   -0.847734\n",
      "3   -0.185211\n",
      "4    0.846920\n",
      "Name: a, dtype: float64\n",
      "          a\n",
      "0  0.585889\n",
      "1 -0.366636\n",
      "2 -0.847734\n",
      "3 -0.185211\n",
      "4  0.846920\n",
      "<class 'pandas.core.frame.DataFrame'>\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:34:06.575471Z",
     "start_time": "2025-01-07T06:34:06.567936Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 不连续索引\n",
    "print(df_obj[['a','c']])"
   ],
   "id": "e198c5b131a0722c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          a         c\n",
      "0  0.585889  0.439963\n",
      "1 -0.366636 -1.367335\n",
      "2 -0.847734 -0.462312\n",
      "3 -0.185211 -0.849396\n",
      "4  0.846920  0.137463\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:34:21.017992Z",
     "start_time": "2025-01-07T06:34:21.002374Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 标签索引 loc\n",
    "# Series\n",
    "print(ser_obj['b':'d'])\n",
    "print(ser_obj.loc['b':'d'])\n",
    "# DataFrame\n",
    "print(df_obj['a'])\n",
    "# 第一个参数索引行， 第二个参数是列\n",
    "print(df_obj.loc[0:2, 'a'])"
   ],
   "id": "f49280ae7c923db",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n",
      "0    0.585889\n",
      "1   -0.366636\n",
      "2   -0.847734\n",
      "3   -0.185211\n",
      "4    0.846920\n",
      "Name: a, dtype: float64\n",
      "0    0.585889\n",
      "1   -0.366636\n",
      "2   -0.847734\n",
      "Name: a, dtype: float64\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:35:00.216377Z",
     "start_time": "2025-01-07T06:35:00.207213Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 整型位置索引 iloc\n",
    "# Series\n",
    "print(ser_obj[1:3])\n",
    "print(ser_obj.iloc[1:3])\n",
    "# DataFrame\n",
    "print(df_obj.iloc[0:2, 0]) # 注意和 df_obj.loc[0:2, 'a']的区别"
   ],
   "id": "af378ae4a471dd44",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b    1\n",
      "c    2\n",
      "dtype: int64\n",
      "b    1\n",
      "c    2\n",
      "dtype: int64\n",
      "0    0.585889\n",
      "1   -0.366636\n",
      "Name: a, dtype: float64\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "5 Pandas 的对齐运算",
   "id": "5e35e5e30517fa50"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:42:19.632701Z",
     "start_time": "2025-01-07T06:42:19.610836Z"
    }
   },
   "cell_type": "code",
   "source": [
    "s1 = pd.Series(range(10, 20), index = range(10))\n",
    "s2 = pd.Series(range(20, 25), index = range(5))\n",
    "print('s1: ' )\n",
    "print(s1)\n",
    "print('')"
   ],
   "id": "132cc98176d521e8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s1: \n",
      "0    10\n",
      "1    11\n",
      "2    12\n",
      "3    13\n",
      "4    14\n",
      "5    15\n",
      "6    16\n",
      "7    17\n",
      "8    18\n",
      "9    19\n",
      "dtype: int64\n",
      "\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:42:42.258676Z",
     "start_time": "2025-01-07T06:42:42.242535Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print('s2: ')\n",
    "print(s2)"
   ],
   "id": "1d06f7a1055a011e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s2: \n",
      "0    20\n",
      "1    21\n",
      "2    22\n",
      "3    23\n",
      "4    24\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:43:08.241873Z",
     "start_time": "2025-01-07T06:43:08.233439Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Series 对齐运算\n",
    "print('s1+s2: ')\n",
    "print(s1+s2)"
   ],
   "id": "3d3729c40adf9ed3",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s1+s2: \n",
      "0    30.0\n",
      "1    32.0\n",
      "2    34.0\n",
      "3    36.0\n",
      "4    38.0\n",
      "5     NaN\n",
      "6     NaN\n",
      "7     NaN\n",
      "8     NaN\n",
      "9     NaN\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:49:23.150082Z",
     "start_time": "2025-01-07T06:49:23.128070Z"
    }
   },
   "cell_type": "code",
   "source": [
    "df1 = pd.DataFrame(np.ones((2,2)), columns = ['a', 'b'])\n",
    "df2 = pd.DataFrame(np.ones((3,3)), columns = ['a', 'b', 'c'])\n",
    "print('df1: ')\n",
    "print(df1)\n",
    "print('')\n",
    "print('df2: ')\n",
    "print(df2)"
   ],
   "id": "50943df290a215dc",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "df1: \n",
      "     a    b\n",
      "0  1.0  1.0\n",
      "1  1.0  1.0\n",
      "\n",
      "df2: \n",
      "     a    b    c\n",
      "0  1.0  1.0  1.0\n",
      "1  1.0  1.0  1.0\n",
      "2  1.0  1.0  1.0\n"
     ]
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:49:31.945162Z",
     "start_time": "2025-01-07T06:49:31.923853Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# DataFrame 对齐操作\n",
    "print('df1+df2: ')\n",
    "print(df1+df2)"
   ],
   "id": "82e95558aa6952a4",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "df1+df2: \n",
      "     a    b   c\n",
      "0  2.0  2.0 NaN\n",
      "1  2.0  2.0 NaN\n",
      "2  NaN  NaN NaN\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T06:50:03.655550Z",
     "start_time": "2025-01-07T06:50:03.636154Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#fill_value\n",
    "print(s1)\n",
    "print(s2)\n",
    "print(s1.add(s2, fill_value = 0))\n",
    "print(df1)\n",
    "print(df2)\n",
    "print(df1.sub(df2, fill_value = 2.))"
   ],
   "id": "934caef71ecdc79c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    10\n",
      "1    11\n",
      "2    12\n",
      "3    13\n",
      "4    14\n",
      "5    15\n",
      "6    16\n",
      "7    17\n",
      "8    18\n",
      "9    19\n",
      "dtype: int64\n",
      "0    20\n",
      "1    21\n",
      "2    22\n",
      "3    23\n",
      "4    24\n",
      "dtype: int64\n",
      "0    30.0\n",
      "1    32.0\n",
      "2    34.0\n",
      "3    36.0\n",
      "4    38.0\n",
      "5    15.0\n",
      "6    16.0\n",
      "7    17.0\n",
      "8    18.0\n",
      "9    19.0\n",
      "dtype: float64\n",
      "     a    b\n",
      "0  1.0  1.0\n",
      "1  1.0  1.0\n",
      "     a    b    c\n",
      "0  1.0  1.0  1.0\n",
      "1  1.0  1.0  1.0\n",
      "2  1.0  1.0  1.0\n",
      "     a    b    c\n",
      "0  0.0  0.0  1.0\n",
      "1  0.0  0.0  1.0\n",
      "2  1.0  1.0  1.0\n"
     ]
    }
   ],
   "execution_count": 24
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
